/**
 * Created by DELL on 2017/6/1.
 */


import React from 'react';
import
{
    View,
    Text,
    TouchableHighlight,
    Image,
    ScrollView,
    WebView,
    TextInput,
    Picker,
    Modal,
    ListView,
    TouchableWithoutFeedback,
    Linking,
}
    from 'react-native';

import  BaseComponent, {base,AppCustomDialog,AppIndictor} from '../../base/Base' ;

let {
    USER_DEFAULT_ADDRESS,//用户默认地址 key值字段
    KEY_PHONE,//
} = base.fields;
let {
    N015_ORDERS$_CREATE_ORDERS,//创建订单
    N034_USERS$_GET_ADDRESS,//获取用户地址
} = base.requests;
//商品详情
export default class GoodsOrderPage extends BaseComponent {
    constructor(props) {
        super(props);
        let bbbb = this.props.navigation.state.params.goodDetail
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        this.state = {
            goodId: this.props.navigation.state.params.goodId,
            goodData: bbbb,
            serviceDate: ds.cloneWithRows(bbbb.serviceDate),
            serviceTimeValues: ds.cloneWithRows(bbbb.serviceTimeValues),
            images: bbbb.images,
            userAddress: null,
            // userAddress: {'name':'测试',
            //     'cellPhone':'13585868374',
            //     'province':'上海',
            //     'city':'上海市',
            //     'district':'黄浦区',
            //     'details':'测试地址',
            //      'id':'69918898-3363-4d9e-91ad-5ac21208d6b6'},
            phone: '',
            beizhu: '',
            unitePrice: parseFloat(bbbb.unitPrice),
            totalPrice: parseFloat(bbbb.unitPrice),
            serviceFee: parseFloat(bbbb.servicePrice),
            totalCount: 1,
            minCount: parseInt(bbbb.startAmount),
            dateAndTime: '请选择日期和时间',
            modalVisible: false,
            dateValue: '',
            timeValue: '',
            appDialogVisible:false,
            showIndictor:false,

        };


    };

    static navigationOptions = ({navigation}) => ({
        //动态设置标题
        // title: navigation.state.params.goodId,
        title: '确认订单',
    });

    componentDidMount() {
        this._setTotalPrice();

        this.getUserDefaultAddress();
    }

    getUserDefaultAddress() {
        base.network.getUipData(N034_USERS$_GET_ADDRESS, {}, (success) => {
            this.setState({
                userAddress: success[0],
            })
        }, (error) => {
            alert(JSON.stringify(error))
        })
    }

    //设置用户的默认地址
    _setUserAddress() {
        let address = this.state.userAddress;
        //有默认地址
        if (address) {

            return (
                <TouchableHighlight onPress={() => {
                    this._selectAddress()
                }}>
                    <View style={{backgroundColor: '#fff', marginTop: 1, padding: 15}}>
                        <View style={{flexDirection: 'row', marginTop: 1}}>
                            <Image style={{width: 15, height: 15, marginRight: 10,}}
                                   source={require('../../imgs/goods/address_name.png')}/>
                            <Text>{address.name + '    ' + address.cellPhone}</Text>
                        </View>

                        <View style={{flexDirection: 'row', marginTop: 5}}>
                            <Image style={{width: 15, height: 15, marginRight: 10,}}
                                   source={require('../../imgs/goods/address.png')}/>
                            <Text>{address.province + '  ' + address.city + '  ' + address.district + '  ' + address.details}</Text>
                        </View>
                    </View>
                </TouchableHighlight>

            )
        } else {
            //没有默认地址
            return (
                <TouchableHighlight onPress={this._selectAddress.bind(this)}>
                    <View
                        style={{
                            backgroundColor: '#fff', marginTop: 1,
                            justifyContent: 'center', alignItems: 'center',
                            height: 55
                        }}>
                        <Text  >请选择地址</Text>
                    </View>
                </TouchableHighlight>

            )
        }
    }


    _selectAddress() {
        this.props.navigation.navigate('Address', {
            isFromOrder: true,
            callback: (data) => {
                this.setState({
                    userAddress: data,
                })
            }
        })
    }

    _setTotalPrice() {
        let aa = this.state.unitePrice;
        let bb = this.state.totalCount;
        let cc = aa * bb;

        this.setState({
            totalPrice: cc,
        })
    }

    _onPressReduce() {
        if (this.state.totalCount <= this.state.minCount) {
            base.toastShort('最低限购数量为：' + this.state.minCount)
            return;
        }
        let aa = this.state.totalCount - 1;
        this.state.totalCount = aa;
        this._setTotalPrice();
    }

    _onPressPlus() {
        let aa = this.state.totalCount + 1;

        this.state.totalCount = aa;
        this._setTotalPrice();
    }

    //设置商品 简介
    _setGoodsInfo() {
        var goodData = this.state.goodData;
        let serviceFee = this.state.serviceFee;

        if (isNaN(serviceFee)) {
            serviceFee = 0.00;
        }
        if (goodData) {
            return (
                <View style={{backgroundColor: '#fff', marginTop: 5}}>


                    <View style={{flexDirection: 'row', padding: 10, paddingLeft: 15, marginTop: 2}}>
                        <Text>上门时间</Text>
                        <View style={{
                            flex: 1,
                            justifyContent: 'flex-end',
                            flexDirection: 'row',
                            alignItems: 'flex-start'
                        }}>
                            {this._getTimePick()}

                        </View>

                    </View>
                    <View style={{backgroundColor: '#DEDEDE', height: 5}}/>

                    <View style={{flexDirection: 'row', padding: 10, paddingLeft: 15, alignItems: 'center'}}>
                        <Image style={{width: 15, height: 15, marginRight: 10,}}
                               source={{uri: goodData.category.iconUrl}}/>
                        <Text>{goodData.category.name}</Text>
                    </View>

                    <View style={{flexDirection: 'row', padding: 10, paddingLeft: 15, backgroundColor: '#f5f5f5'}}>
                        <Image style={{width: 40, height: 40, marginRight: 10,}}
                               source={{uri: goodData.iconUrl}}/>
                        <Text>{goodData.name}</Text>
                        <View style={{flex: 1, alignItems: 'flex-end'}}>
                            <Text >¥ {goodData.unitPrice}</Text>
                        </View>
                    </View>

                    <View style={{flexDirection: 'row', padding: 10, paddingLeft: 15, marginTop: 2}}>
                        <Text>数量</Text>
                        <View style={{flex: 1, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center'}}>
                            <Text style={{width: 20, height: 20, backgroundColor: '#f5f5f5', marginRight: 10}}
                                  onPress={() => this._onPressReduce()}
                            > - </Text>
                            <Text >{this.state.totalCount}</Text>
                            <Text style={{width: 20, height: 20, backgroundColor: '#f5f5f5', marginLeft: 10}}
                                  onPress={() => this._onPressPlus()}
                            > + </Text>
                        </View>

                    </View>
                    <View style={{backgroundColor: '#DEDEDE', height: 1}}/>

                    <View style={{flexDirection: 'row', padding: 10, paddingLeft: 15, marginTop: 2}}>
                        <Text>小计</Text>
                        <View style={{flex: 1, alignItems: 'flex-end'}}>
                            <Text >¥ {this.state.totalPrice}</Text>
                        </View>

                    </View>


                    <View style={{
                        flexDirection: 'row',
                        paddingBottom: 10,
                        paddingRight: 10,
                        paddingLeft: 15,
                        marginTop: 2
                    }}>
                        <Text>服务费</Text>
                        <View style={{flex: 1, alignItems: 'flex-end'}}>
                            <Text >¥ {serviceFee}</Text>
                        </View>

                    </View>

                    <View style={{backgroundColor: '#DEDEDE', height: 5}}/>

                    <View style={{padding: 10, paddingLeft: 15, marginTop: 2}}>
                        <Text>备注</Text>

                        <TextInput
                            placeholder={'可以添加需求备注'}
                            clearButtonMode='while-editing'
                            underlineColorAndroid={'transparent'}
                            style={{
                                textAlignVertical: 'top',
                                minHeight: 80,
                                backgroundColor: '#f5f5f5',
                                color: '#808080',
                                fontSize: 14,
                            }}

                            onChangeText={(text) => {
                                return this.setState({
                                    beizhu: text,
                                })
                            }}
                            value={this.state.beizhu}
                        />

                    </View>

                </View>
            )
        }
    }

    _getTimePick() {
        let aaa = this.state.dateValue;
        if (!aaa) {
            aaa = this.state.dateAndTime;
        } else {
            aaa = this.state.dateValue + '  ' + this.state.timeValue;
        }
        return (
            <View >
                <Modal
                    animationType={"slide"}
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={() => {
                    }}
                >
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center',backgroundColor:'rgba(0,0,0,0.3)'}}>
                        <View style={{
                            width: 300,
                            height: 200,
                            justifyContent: 'center',
                            alignItems: 'center',
                            backgroundColor: '#fff',
                            borderRadius:5,

                        }}>
                            <View style={{flexDirection: 'row', height: '80%'}}>
                                <ListView
                                    contentContainerStyle={{alignItems:'center'}}
                                    dataSource={this.state.serviceDate}
                                    renderRow={(rowData) => {
                                        return <Text onPress={() => {
                                            this.setState({dateValue: rowData})
                                        }}>{rowData}</Text>
                                    }}
                                    stickySectionHeadersEnabled={true}
                                />
                                <View style={{width:1,backgroundColor:'#dedede'}}/>
                                <ListView
                                    contentContainerStyle={{alignItems:'center'}}
                                    dataSource={this.state.serviceTimeValues}
                                    renderRow={(rowData) => {
                                        return <Text onPress={() => {
                                            if (this.state.dateValue) {
                                                let bbb = this.state.dateAndTimeValue;
                                                this.setState({
                                                    timeValue: rowData,
                                                    modalVisible: false,
                                                })

                                            } else {
                                                base.toastShort('请先选择日期')
                                            }
                                        }}>{rowData}</Text>
                                    }}
                                    stickySectionHeadersEnabled={true}
                                />
                            </View>
                            <Text
                                style={{marginTop:10,marginBottom:5}}
                                onPress={() => {
                                this.setState({modalVisible: false})
                            }}>取消</Text>
                        </View>

                    </View>

                </Modal>

                <TouchableHighlight
                    onPress={() => {
                    this.setState({modalVisible: true});
                }}>
                    <Text>{aaa}</Text>
                </TouchableHighlight>

            </View>
        )

    }


    _setBottomView() {
        return (
            <View  style={{height: '100%',flex:1,flexDirection:'row'}}>
                <TouchableWithoutFeedback onPress={() => {
                    this._setAppDialogVisiale(true)
                }}>
                    <View style={{flex:1,backgroundColor:'#d7e1ff',justifyContent:'center',alignItems:'center'}}>
                        <Text >联系客服</Text>
                    </View>

                </TouchableWithoutFeedback>
                <TouchableWithoutFeedback onPress={() => {
                    this._createOrder()
                }}>
                    <View style={{flex:1,backgroundColor:'#ff6138',justifyContent:'center',alignItems:'center'}}>
                        <Text style={{color:'#fff'}}>确认下单</Text>
                    </View>

                </TouchableWithoutFeedback>

            </View>
        )
    }

    _toConnectPhone(){
       Linking.canOpenURL('tel:10086')
           .then(support=>{
               if(support){
                   return Linking.openURL('tel:10086')
               }else {
                   alert('不支持打电话')
               }
           })
           .catch(error=>{
               alert('error'+error)
           })
    }
    //TODO
    _createOrder() {
        let orderDetails = this.state.goodData;
        if (!orderDetails) {
            base.toastShort('数据异常，请返回重试')
            return
        }
        if (!this.state.userAddress) {
            base.toastShort('请选择送货地址')
            return
        }
        if (!this.state.dateValue || !this.state.timeValue) {
            base.toastShort('请选择上门时间')
            return
        }
        let params = {
            "ServiceTimeCategory": orderDetails.serviceTimeCategory,
            "AddressId": this.state.userAddress.id,
            "ServiceDate": this.state.dateValue,
            "Comments": this.state.beizhu,
            "ServiceCategoryId": orderDetails.category.id,
            "CompanyId": orderDetails.company.id,
            // "CouponId": '',
            "ItemDetails": orderDetails.id + ';' + this.state.totalCount,
            "ServiceTimeValues": this.state.timeValue,
        }
        this._setAppIndictor(true)
        base.network.getUipData(N015_ORDERS$_CREATE_ORDERS, params, (success) => {
                this._setAppIndictor(false)
                this.props.navigation.navigate('PayPage', {isFromOrder: true, orderId: success.id})

            },
            (error) => {
                this._setAppIndictor(false)
                alert("下单失败" + error)
            },
        )
    }

    _setAppDialogVisiale(visible){
        this.setState({
            appDialogVisible:visible,
        })
    }

    _setAppIndictor(visible){
        this.setState({
            showIndictor:visible,
        })
    }

    render() {
        return (
            <View>

                <AppCustomDialog
                    dialogMessage="是否要拨打电话联系客服？"
                    modalVisible={this.state.appDialogVisible}
                    dialogOnLeftTitle="再考虑下"
                    dialogOnRightTitle="立即行动"
                    onLeftPress={()=>{this._setAppDialogVisiale(false)}}
                    onRightPress={()=>{this._setAppDialogVisiale(false),this._toConnectPhone()}}
                />

                <AppIndictor
                    modalVisible={this.state.showIndictor}
                    text="下单中..."
                />

                <ScrollView style={{height: '92%', marginBottom: 1}}>
                    {this._setUserAddress()}
                    {this._setGoodsInfo()}

                </ScrollView>
                <View style={{height: '8%'}}>
                    {this._setBottomView()}
                </View>


            </View>


        )
    }

}
